package indi.kider.server.employee.service;

import indi.kider.common.constant.AppUserType;
import indi.kider.common.model.apabus.Rent;
import indi.kider.common.model.apartment.DevLock;
import indi.kider.common.model.employee.*;
import indi.kider.server.apartment.mapper.DevLockMapper;
import indi.kider.server.employee.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@SuppressWarnings("ALL")
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private WaiterMapper waiterMapper;
    @Autowired
    private WorkerMapper workerMapper;
    @Autowired
    private TenantService tenantService;
    @Autowired
    private DevLockMapper devLockMapper;

    @Override
    public void insert(String phone, Integer role) {
        User q = new User();
        q.setPhone(phone);
        List<User> users = userMapper.select(q);
        if (users != null && !users.isEmpty() && users.get(0) != null) {
            User user = users.get(0);
            String roleStr = user.getRole();
            String[] roleArray = roleStr.split(",");
            roleArray[roleArray.length] = String.valueOf(role);
            user.setRole(String.join(",", roleArray));
            userMapper.updateByPrimaryKeySelective(user);
        } else {
            q.setPwd("123456");
            q.setRole(String.valueOf(role));
            userMapper.insert(q);
        }
    }

    @Override
    public void del(String phone, Integer role) {
        User q = new User();
        q.setPhone(phone);
        List<User> users = userMapper.select(q);
        if (users != null && !users.isEmpty() && users.get(0) != null) {
            User user = users.get(0);
            String roleStr = user.getRole();
            String[] roleArray = roleStr.split(",");
            String[] newRoleArry = {};
            for (int i = 0; i < roleArray.length; i++) {
                if (!roleArray[i].equals(String.valueOf(role))) {
                    newRoleArry[newRoleArry.length] = roleArray[i];
                }
            }
            if (newRoleArry.length == 0) {
                userMapper.delete(user);
            } else {
                user.setRole(String.join(",", newRoleArry));
                userMapper.updateByPrimaryKeySelective(user);
            }

        }
    }
    @Override
    public AppUser getRelatedUser(String phone, Integer role) throws Exception {
        AppUser appUser = xxgetRelatedUser(phone, role);
        /* 查询一下锁具的情况*/
        Long housesId = appUser.getRent().getHousesId();
        DevLock devLock = new DevLock();
        devLock.setHouseId(housesId);
        List<DevLock> tempList = devLockMapper.select(devLock);
        if ((tempList != null) && !(tempList.isEmpty())){
            devLock = tempList.get(0);
            appUser.setDevLock(devLock);
        }
        return appUser;
    }

    AppUser xxgetRelatedUser(String phone, Integer role) throws Exception {
        if (role.equals(AppUserType.TENANT) || role.equals(AppUserType.FRIEND)) {
            Tenant queryT = new Tenant();
            queryT.setPhone(phone);
            Tenant tenant = tenantMapper.selectOne(queryT);

            if (tenant != null && tenant.getId() > 0) {
                Rent rent;
                try {
                    rent = tenantService.getTenantRent(phone);
                } catch (Exception e) {
                    if (e.getMessage().contains("selectOne()"))
                        throw new Exception("当前租客存在多条有效租房记录");
                    else throw e;
                }
                AppUser appUser;
                if (tenant.getMainId() != null && tenant.getMainId() > 0)
                    appUser = new AppUser(AppUserType.FRIEND, tenant, tenantMapper.selectByPrimaryKey(tenant.getMainId()));
                else appUser = new AppUser(AppUserType.TENANT, tenant);
                appUser.setRent(rent);
                return appUser;
            }
        } else if (role.equals(AppUserType.LANDLORD)) {
            Employee queryE = new Employee();
            queryE.setPhone(phone);
            Employee employee = employeeMapper.selectOne(queryE);
            if (employee != null && employee.getId() > 0) {
                employee.setPwd("");
                return new AppUser(AppUserType.LANDLORD, employee);
            }
        } else if (role.equals(AppUserType.WAITER)) {
            Waiter queryW = new Waiter();
            queryW.setPhone(phone);
            Waiter waiter = waiterMapper.selectOne(queryW);
            if (waiter != null && waiter.getId() > 0)
                return new AppUser(AppUserType.WAITER, waiter);
        } else {
            Worker queryWr = new Worker();
            queryWr.setPhone(phone);
            Worker worker = workerMapper.selectOne(queryWr);
            if (worker != null && worker.getId() > 0)
                return new AppUser(AppUserType.WORKER, worker);
            else throw new Exception("手机号码未注册！");
        }
        return null;
    }

    @Override
    public void modify(String phone, String oldPwd, String newPwd) throws Exception {
        User q = new User();
        q.setPhone(phone);
        q.setPwd(oldPwd);
        List<User> users = userMapper.select(q);
        if (users != null && !users.isEmpty() && users.get(0) != null) {
            User user = users.get(0);
            user.setPwd(newPwd);
            userMapper.updateByPrimaryKeySelective(user);
        } else throw new Exception("请确认原密码正确！");
    }

    @Override
    public void modify(String oldPhone, String newPhone) {
        User q = new User();
        q.setPhone(oldPhone);
        List<User> users = userMapper.select(q);
        if (users != null && !users.isEmpty() && users.get(0) != null) {
            User user = users.get(0);
            user.setPhone(newPhone);
            userMapper.updateByPrimaryKeySelective(user);
        }
    }

    @Override
    public AppUser login(String phone, String pwd) throws Exception {
        AppUser appUser = new AppUser();
        User q = new User();
        q.setPhone(phone);
        //q.setPwd(pwd);
        List<User> users = userMapper.select(q);
        if (users != null && !users.isEmpty() && users.get(0) != null) {
            q = users.get(0);
            if (!pwd.equals(q.getPwd()))
                throw new Exception("密码不正确！");
            if (q.getRole().length() > 2) {
                appUser.setType(0);
                q.setPwd("");
                appUser.setAppUser(q);
            } else {
                appUser = getRelatedUser(phone, Integer.valueOf(q.getRole()));
            }
        } else throw new Exception("用户名密码不匹配！");

        return appUser;
    }
}
